<template>
  <div class="table-sty box-shadow">
    <div class="trbtable">
      <el-table
        class="outTable"
        v-loading="loading"
        :data="tableData"
        @expand-change="handleExpandChange"
        :empty-text="emptyText()"
        row-key="id"
        :expand-row-keys="expands"
        :default-sort = "{prop: 'createTs', order: 'descending'}"
        style="width: 100%">
        <!-- 详情 -->
        <el-table-column type="expand" width="1">
          <template slot-scope="props">
            <div class="box-shadow" style="margin: 0 80px; background: rgba(0,0,0,0.1);">
              <el-table
                class="innerTable"
                :data="dataDetail"
                v-loading="loading_detail"
                style="width: 100%;">
                <!-- 成交时间 -->
                <el-table-column :label="$t('order.subAvgTime')">
                  <template slot-scope="props">
                    {{props.row.dealTime | dateFormatBIH}}
                  </template>
                </el-table-column>
                <!-- 成交价 -->
                <el-table-column :label="$t('order.subAvgPrice')">
                  <template slot-scope="props">
                    {{props.row.dealPriceStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
                  </template>
                </el-table-column>
                <!-- 成交量 -->
                <el-table-column :label="$t('order.subAvgCount')" >
                  <template slot-scope="props">
                    {{props.row.dealCountStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi1}}</span>
                  </template>
                </el-table-column>
                <!-- 成交金额 -->
                <el-table-column :label="$t('order.subAvgMoney')" >
                  <template slot-scope="props">
                    {{props.row.dealAmountStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
                  </template>
                </el-table-column>
                <!-- 手续费 -->
                <el-table-column :label="$t('order.subBidCharge')" >
                  <template slot-scope="props">
                    <span v-if="props.row.direction === 2">
                      {{props.row.askChargeStr}}
                      <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
                    </span>
                    <span v-if="props.row.direction === 1">
                      {{props.row.bidChargeStr}}
                      <span class="fontx wordWrap" style="color: #999">{{props.row.bi1}}</span>
                    </span>
                  </template>
                </el-table-column>
                <!-- 节省手续费 -->
                <el-table-column :label="$t('ndxStake.saveFee')" width="130px" v-if="$appName === 'eosNewdex'">
                  <template slot-scope="props">
                    <span v-if="props.row.direction === 2">
                      {{props.row.askSaveChargeStr || '0'}}
                      <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
                    </span>
                    <span v-if="props.row.direction === 1">
                      {{props.row.bidSaveChargeStr || '0'}}
                      <span class="fontx wordWrap" style="color: #999">{{props.row.bi1}}</span>
                    </span>
                  </template>
                </el-table-column>
                <!-- 操作 -->
                <el-table-column :label="$t('order.operation')" width="100px">
                  <template slot-scope="props">
                    <el-button type="text"
                    @click="handleOrderSuccessDetail(props.row)">{{$t('jy.jydetail')}}</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <!-- 币种 -->
        <el-table-column :label="$t('order.coinCode')" width="155px">
          <template slot-scope="props">
            <span class="symbolCoinCode newCoin flexc" @click="handleSymbolJump(props.row)">
              <span class="redDot" v-if="!props.row.readStatus"></span>
              <!-- https://ndi.340wan.com/eos/newdexissuer-ndx.png -->
              <div class="newCoinImg"
              :class="{'tradeImg' : $route.name === 'embedTrade',
              'newCoinImgForTron' : $appName === 'tronNewdex'}">
              <img v-if="$appName === 'eosNewdex'
                && props.row.valuationCoinContract === 'issue.newdex'
                && props.row.contract !== 'issue.newdex'"
                :src="`https://ndi.340wan.com/${props.row.baseChain}/${parseSymbol(props.row.symbol, props.row.valuationCoinContract)[0].toLowerCase() || ''}-${(parseSymbol(props.row.symbol, props.row.valuationCoinContract)[1].toUpperCase() || '').toLowerCase()}.png`" alt="">
                <img alt=""
                v-else-if="$appName === 'eosNewdex'
                && props.row.valuationCoinContract === 'issue.newdex'"
                :src="`https://ndi.340wan.com/${props.row.baseChain}/${props.row.valuationCoinContract}-${(parseSymbol(props.row.symbol, props.row.contract)[1].toUpperCase() || '').toLowerCase()}.png`">
                <img :src="`https://ndi.340wan.com/${props.row.baseChain}/${props.row.valuationCoinContract}-${(parseSymbol(props.row.symbol, props.row.valuationCoinContract)[1].toUpperCase() || '').toLowerCase()}.png`"
                v-else-if="$appName === 'eosNewdex'
                && (props.row.valuationCoinContract === 'bitpietokens' || props.row.valuationCoinContract === 'enu.token')
                && parseSymbol(props.row.symbol, props.row.valuationCoinContract)[1].toUpperCase() !== 'EOS'"
                alt="">
                <img :src="`https://ndi.340wan.com/${props.row.baseChain}/${props.row.valuationCoinContract}-${(parseSymbol(props.row.symbol, props.row.valuationCoinContract)[2].toUpperCase() || '').toLowerCase()}.png`"
                v-else-if="$appName === 'eosNewdex' &&
                props.row.valuationCoinContract !== 'eosio.token' &&
                props.row.valuationCoinContract !== 'tethertether' &&
                props.row.valuationCoinContract !== 'issue.newdex'"
                alt="">
                <!-- <img src="@/assets/img/eos.png" v-else> -->
                <img :src="`https://ndi.340wan.com/tron/${parseSymbol(props.row.symbol, props.row.bi1)[0].toLowerCase() || ''}.png`"
                v-else-if="$appName === 'tronNewdex'" alt="">
                <img :src="`https://ndi.340wan.com/${props.row.baseChain}/${parseSymbol(props.row.symbol, props.row.baseCoinContract)[0].toLowerCase() || ''}-${(parseSymbol(props.row.symbol, props.row.valuationCoinContract)[1].toUpperCase() || '').toLowerCase()}.png`" alt=""
                v-else-if="props.row.valuationCoinContract === 'issue.newdex'">
                <img :src="`https://ndi.340wan.com/${props.row.baseChain}/${parseSymbol(props.row.symbol, props.row.valuationCoinContract)[0].toLowerCase() || ''}-${(parseSymbol(props.row.symbol, props.row.valuationCoinContract)[1].toUpperCase() || '').toLowerCase()}.png`" alt="" v-else>
              </div>
              <span style="color: #278EDA;" class="symbolCoin">{{props.row.bi1}} / {{props.row.bi3}}</span>
            </span>
          </template>
        </el-table-column>
        <!-- 方向 -->
        <el-table-column :label="$t('order.direction')" width="50px">
          <template slot-scope="props">
            <span v-if="props.row.direction === 1" class="color-green">{{$t('order.buy')}}</span>
            <span v-if="props.row.direction === 2" class="color-red">{{$t('order.sell')}}</span>
          </template>
        </el-table-column>
        <!-- 委托时间 -->
        <el-table-column :label="$t('order.entrustmentTime')" width="133px">
          <template slot-scope="props">
            {{props.row.orderTime | dateFormatBIH}}
          </template>
        </el-table-column>
        <!-- 委托价 -->
        <el-table-column :label="$t('order.entrustmentPrice')" width="130px">
          <template slot-scope="props">
            <span v-if="props.row.type === 1">
              {{props.row.orderPriceStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
            </span>
            <span style="color: #999" v-else> {{$t('jy.shijia')}} </span>
          </template>
        </el-table-column>
        <!-- 成交均价 -->
        <el-table-column :label="$t('order.avgPrice')" width="128px">
          <template slot-scope="props">
            <span v-if="props.row.dealPriceStr">
              {{props.row.dealPriceStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
            </span>
            <span class="nodataj" v-else>—</span>
          </template>
        </el-table-column>
        <!-- 委托总量 -->
        <el-table-column :label="$t('order.entrustmentCount')" width="165px">
          <template slot-scope="props">
            <span v-if="props.row.type === 1 || (props.row.type === 2 && props.row.direction === 2)">
              {{props.row.orderCountStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi1}}</span>
            </span>
            <span style="color: #999"  v-if="props.row.type === 2 && props.row.direction === 1">—</span>
          </template>
        </el-table-column>
        <!-- 成交量 -->
        <el-table-column :label="$t('order.avgCount')" width="165px">
          <template slot-scope="props">
            <span v-if="props.row.dealCountStr">
              {{props.row.dealCountStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi1}}</span>
            </span>
            <span class="nodataj" v-else>—</span>
          </template>
        </el-table-column>
        <!-- 成交金额 -->
        <el-table-column :label="$t('order.subAvgMoney')" width="120px">
          <template slot-scope="props">
            <span v-if="props.row.dealAmountStr">
              {{props.row.dealAmountStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
            </span>
            <span class="nodataj" v-else>—</span>
          </template>
        </el-table-column>
        <!-- 状态 -->
        <el-table-column :label="$t('order.avgType2')" width="127px">
          <template slot-scope="props">
            <div>
              <span class="colorThis" v-if="props.row.dealStatus === 0 && props.row.orderStatus === 0">{{$t('order.noDeal')}}</span>
              <span v-if="props.row.dealStatus === 0 && props.row.orderStatus === -1">{{$t('order.failure')}}</span>
              <span v-if="props.row.dealStatus === 0 && props.row.orderStatus === 2">{{$t('order.rescinded')}}</span>
              <span class="colorThis" v-if="props.row.dealStatus === 1 && props.row.orderStatus === 0">{{$t('order.partDeal')}}</span>
              <span v-if="props.row.dealStatus === 1 && props.row.orderStatus === 2">
                {{$t('order.partDeal')}}[{{$t('order.rescinded')}}]</span>
              <span v-if="props.row.dealStatus === 2">{{$t('order.allDeal')}}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column :label="$t('order.operation')" width="">
          <template slot-scope="props">
            <el-button type="text" @click="handleLookDetail(props.row.id, props.row.symbol, props.row.direction, props.row.readStatus)"
            v-if="props.row.dealStatus !== 0">{{$t('order.detail')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagebox center ptb" v-if="!(!hasDataForTable || (hasDataForTable < 10 && form.currPage === 1))">
        <el-pagination
          @size-change="handleSizeChange"
          :current-page="form.currPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="form.pageSize"
          layout="prev, pager, next, sizes"
          @prev-click="handlePrevPage"
          @next-click="handleNextPage">
        </el-pagination>
      </div>
    </div>
    <!-- 订单成交详情 -->
    <el-dialog
      class="orderDetail"
      title="Newdex"
      :show-close='true'
      :visible.sync="orderDetailVisible"
      width="900px">
      <order-success-detail
      :order-detail-id="orderDetailId"
      @listenDetailClose="orderDetailVisible=false"
      v-if="$appName === 'eosNewdex'"/>
      <tron-success-detail
      :order-detail-id="orderDetailId"
      @listenDetailClose="orderDetailVisible=false"
      v-if="$appName === 'tronNewdex'"/>
    </el-dialog>
  </div>
</template>

<script>
import OrderSuccessDetail from '@/components/OrderSuccessDetail';
import TronSuccessDetail from '@/components/TronSuccessDetail';
import Io from '@/utils/socket';
import { toFixed, parseSymbol } from '@/utils/validate';

export default {
  name: 'history',
  components: {
    OrderSuccessDetail,
    TronSuccessDetail
  },
  data() {
    return {
      loading: false,
      loading_detail: false,
      tradByVuex: null,
      hasDataForTable: 1, // 加载数据中
      active: 0,
      menu: [
        {
          name: 'lsweituo',
          value: 0
        }
      ],
      form: {},
      tableData: [],
      expands: [],
      dataDetail: [],
      listener: null,
      orderDetailVisible: false, // 订单成功详情
      orderDetailId: null, // 订单成功详情id
    };
  },
  props: {
    formDataget: {
      type: Object,
      default: null
    },
    symbolStatusProps: Object,
    embed: {
      type: Boolean,
      default: false
    },
  },
  watch: {
    'formDataget.timerUpdate': function change() {
      this.form = this.formDataget;
      // 监听已撤销订单
      if (this.form.hidRevokeOrder) {
        this.form.totalCount = 0;
        this.form.hideCancelOrder = 1;
      } else {
        this.form.hideCancelOrder = 0;
      }
      this.form.currPage = 1;
      this.handleGetUserOrder();
    },
    '$store.state.app.trade': function change() {
      this.tradByVuex = this.$store.state.app.trade;
      if (this.form.hidOtherKey) {
        this.form.symbolId = this.tradByVuex.id;
      }
      this.handleGetUserOrder();
    },
    '$store.state.app.scatter.identity': {
      handler: function listen(val) {
        if (!val) return;
        this.form.currPage = 1;
        this.handleGetUserOrder();
      },
      deep: true,
    },
  },
  created() {
  },
  mounted() {
    this.tradByVuex = this.$store.state.app.trade;
    Io.addListenerOrder('start', (res) => {
      this.listener = res.listener;
      if (res.type === 'orderupdate') { // 下单成功
        this.handleGetUserOrder();
        this.$emit('ListenHistoryOrder', 'orderUpdate');
      }
      if (res.type === 'cancelsuccess') { // 撤单成功
        this.handleGetUserOrder();
        this.$emit('ListenHistoryOrder', 'orderUpdate');
      }
    });
    this.form = this.formDataget || {};
    if (this.form && this.form.currPage) {
      this.handleGetUserOrder();
    }
  },
  beforeDestroy() {
    Io.addListenerOrder({ // 停止监听订单信息
      way: 'stop',
      listener: this.listener
    });
  },
  methods: {
    // 空数据
    emptyText() {
      const scat = this.$store.state.app.scatter
      if (scat && !scat.identity) {
        return this.$t('jy.sqhlook');
      }
      return this.hasDataForTable ? this.$t('myWallet.loadData') : this.$t('myWallet.noData');
    },
    // 数字截取 - 保留小数
    handleToFixed(num, p) {
      return toFixed(num, p);
    },
    // 菜单切换
    handleMenuActive(value) {
      this.active = value;
    },
    // 跳转到对应币种
    handleSymbolJump(row) {
      const symbolFormat = parseSymbol(row.symbol);
      const params = {
        id: row.symbolId,
        symbol1: symbolFormat[1].toUpperCase(),
        symbol2: symbolFormat[2].toUpperCase(), // EOS
        symbol1_code: symbolFormat[0], // 交易币种合约
        symbol2_code: 'eosio.token', // EOS合约
        symbol: row.symbol,
      }
      const symbolId = this.$store.state.app.trade.id;
      if ((this.$route.name === 'trade' || this.$route.name === 'embedTrade') && params.id === symbolId) return;
      this.handleToTransaction(params.symbol, params);
    },
    // 跳转
    handleToTransaction(tradRouterParams, params) {
      if (this.$route.name === 'embedTrade') {
        this.$router.push({
          path: `/embed-trade/${tradRouterParams}`
        });
      } else {
        this.$router.push({
          path: `/trade/${tradRouterParams}`
        });
      }
      this.$store.dispatch('setTrade', params);
    },
    // 获取当前委托订单列表
    handleGetUserOrder() {
      const param = this.form;
      this.loading = true;
      this.$http.post('/order/queryHistoryOrderPage', param).then((res) => {
        this.loading = false;
        if (res.code === 401) {
          // 用户未登录
          return;
        }
        if (res.code !== 0) {
          this.$message.error(res.msg);
          return;
        }
        const items = res.page.list;
        if (items.length === 0 && this.form.currPage !== 1) {
          this.$message.warning(this.$t('order.noMoreData'));
          // if (this.form.currPage === 1) return;
          this.form.currPage -= 1;
          return;
        }
        this.tableData = [];
        items.forEach((v) => {
          const vv = v;
          if (v.symbol != null) {
            const bi = parseSymbol(vv.symbol.toUpperCase());
            vv.bi0 = bi[0];
            vv.bi1 = bi[1];
            vv.bi2 = bi[2];
            // meetone侧链名称过长修改名称后缀
            const symbolLength = bi[1].length;
            const codeLength = bi[2].length;
            if (symbolLength + codeLength > 11) {
              vv.bi3 = 'ME...';
            } else {
              vv.bi3 = bi[2];
            }
          }
        });
        this.tableData = items;
        this.form.totalCount = res.page.totalCount;
        this.hasDataForTable = this.tableData.length;
        this.$emit('ListenHistoryOrder', 'orderPage', this.hasDataForTable);
      });
    },
    // 获取当前委托订单详情
    handleGetUserOrderDetail(id, bistr, direction, readStatus) {
      const index = this.tableData.findIndex(v => v.id === id);
      const param = {
        orderId: id,
      };
      const updateParams = {
        orderId: id,
      };
      this.loading_detail = true;
      this.$http.post('/order/getOrderDealRecords', param).then((res) => {
        this.loading_detail = false;
        if (res.code !== 0) {
          this.$message.error(res.msg);
          return;
        }
        const items = res.orderDealRecords;
        const bi = parseSymbol(bistr.toUpperCase());
        items.forEach((v) => {
          const vv = v;
          vv.bi1 = bi[1];
          vv.bi2 = bi[2];
          vv.direction = direction;
        });
        this.dataDetail = items;
      });
      if (readStatus === 0) {
        this.$http.post('/order/updateOrderIsReaded', updateParams).then(() => {
          // if (res.code !== 0) {
          //   this.$message.error(res.msg);
          //   return;
          // }
          this.tableData[index].readStatus = 1;
          this.$store.dispatch('setBadge', 0);
          this.$emit('ListenHistoryOrder', 'orderUpdate');
        });
      }
    },

    // 查看详情
    handleExpandChange(val) {
      const id = val.id;
      const bistr = val.symbol;
      const direction = val.direction;
      const readStatus = val.readStatus;
      this.handleLookDetail(id, bistr, direction, readStatus);
    },
    handleLookDetail(id, bi, direction, readStatus) {
      if (this.expands.find(v => v === id)) {
        this.expands = [];
        return;
      }
      this.expands = [];
      this.expands.push(id);
      this.handleGetUserOrderDetail(id, bi, direction, readStatus);
    },
    // 上一页
    handlePrevPage() {
      // if (this.formData.currPage === 1) return;
      this.form.currPage -= 1;
      this.handleGetUserOrder();
    },
    // 下一页
    handleNextPage() {
      this.form.currPage += 1;
      this.handleGetUserOrder();
    },
    // 去第几页
    handleCurrentChange(page) {
      this.form.currPage = page;
      this.handleGetUserOrder();
    },
    // 改变分页总条数
    handleSizeChange(val) {
      this.form.currPage = 1;
      this.form.pageSize = val;
      this.handleGetUserOrder();
    },
    // 查看具体详情TXID
    handleOrderSuccessDetail(row) {
      // this.$emit('listenDetailAction', true, row.id);
      this.orderDetailId = row.id; // 订单成功详情id
      this.orderDetailVisible = true;
    },
    parseSymbol(a, b) {
      return parseSymbol(a, b)
    }
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/variables.scss";

.nodataj {
  display: inline-block;
  margin-right: 10px;
}

.topcolor {
  background: $-topcolorf7;
}

.trbtable {
  background: #fff;
  // 空数据最小宽度
  /deep/ .el-table__empty-block {
    min-height: 120px;
  }
}

.shuaxin {
  display: inline-block;
  margin: 0;
  font-size: 14px;
  padding: 0px 5px;

  &.act i{
    animation: rotating 1s linear infinite;
  }
}

.wordWrap{
  word-wrap: break-word;
  word-break: normal;
}

.unReadOrder {
  display: inline-block;
  cursor: pointer;
  margin-right: 10px;
  .redDot {
    display: inline-block;
    width: 5px;
    height: 5px;
    background: #E51C23;
    border-radius: 50%;
    margin-bottom: 2px;
  }
}
.theme-278EDA {
  .cell {
    span {
      color: #333;
    }
  }
}

.table-sty.box-shadow {
  box-shadow: none;
}

.theme-1B1D27 {
  .box-shadow {
    border: 1px solid rgba(0, 0, 0, .1);
    box-shadow: none;
    background: $-topcolor;
  }

  .topcolor {
    background: $-topcolor2;
  }
  .symbolCoinCode {
    .symbolCoin {
      color: #7b8db9 !important;
      &:hover {
        font-weight: bold;
      }
    }
  }
  .trbtable {
    background: $-black1;
    /deep/ .cell {
      color: rgba(255, 255, 255, 0.6);
    }
  }
}
.tabpane /deep/.el-checkbox__label {
  color: #666;
  font-size: 12px;
}
.toOrderBtn {
  cursor: pointer;
  color: #278EDA;
}
.table-sty /deep/.el-table {
  font-size: 12px;
  .el-table__header-wrapper {
    font-size: 12px;
  }
  .el-table__empty-text {
    font-size: 12px;
    color: #666;
  }
  .cell {
    font-weight: normal;
    .symbolCoinCode {
      position: relative;
      display: block;
      cursor: pointer;
      color: #3A98DD !important;
      span {
        display: inline-block;
        vertical-align: bottom;
        font-size: 12px !important;
        padding-left: 3px;
        margin-bottom: 2px;
        &:hover {
          font-weight: bold;
        }
      }
      img {
        // display: inline-block;
        // width: 22px;
        vertical-align: middle;
        margin-right: 3px;
        background: #fff;
        border-radius: 50%;
      }
      .redDot {
        position: absolute;
        top: 50%;
        left: -12px;
        width: 6px;
        height: 6px;
        background: #E51C23;
        border-radius: 50%;
        margin-top: -3px;
      }
    }
  }

  .cell span{
    font-size: 12px;
    &:hover {
      // font-weight: bold;
      .contractCode {
        font-weight: normal;
      }
    }
  }
  .el-table__expand-icon {
    visibility: hidden;
  }

  .el-table__body tr .cell,
  .el-table__header tr .cell{
    text-align: right;
  }
  .el-table__header tr .cell{
    color: #999;
  }
  .el-table__body tr td:nth-child(2) .cell,
  .el-table__header tr th:nth-child(2) .cell,
  .el-table__body tr td:nth-child(4) .cell,
  .el-table__header tr th:nth-child(4) .cell,
  .el-table__body tr td:nth-child(11) .cell,
  .el-table__header tr th:nth-child(11) .cell,
  .el-table__body tr td:nth-child(10) .cell,
  .el-table__header tr th:nth-child(10) .cell {
    text-align: center;
  }

  .el-table__body tr td:nth-child(10) .cell {
    padding: 0 5px;
  }

  .el-table__body tr td:nth-child(2) .cell {
    text-align: left;
    // text-indent: 1em;
    padding: 6px 10px 6px 18px;
    line-height: 16px;
  }
  .el-table__header tr th:nth-child(2) .cell {
    text-align: left;
    text-indent: 0.7em;
  }
  .el-table__body tr td:nth-child(11) .cell {
    .el-button {
      font-weight: 400;
      &:hover {
        font-weight: bold;
      }
    }
  }

  .innerTable{
    .el-table__body tr td .cell,
    .el-table__header tr th .cell{
      text-align: right;
    }

    .el-table__body tr td:nth-child(1) .cell,
    .el-table__header tr th:nth-child(1) .cell{
      text-align: center;
    }

    .el-table__body tr td:nth-child(5) .cell,
    .el-table__header tr th:nth-child(5) .cell{
      padding-right: 50px;
    }
  }
}
</style>

